#coding:utf-8
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth, messages
from settings import GROUP_PAGE_SIZE
from utils import *
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.cache import cache
from models import *
from forms import *
from django.utils.html import escape
from django.db import transaction
from django.views.decorators.csrf import csrf_protect
from django.template.context import RequestContext
import datetime
from urllib import urlencode
@csrf_protect  
@never_cache
def topic(request,tid):
    topic = Topic.objects.detail(tid)
    replies = Comment.objects.topic_replies(tid)
    alert = request.GET.get('alert') or ""
    group = topic.group
    return render_to_response('topic.html', locals())  


@never_cache
@transaction.commit_on_success
def add_topic(request):
    gid = request.GET.get("groupid") or request.POST.get("groupid")
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/topic/add/?groupid=%s'%gid}))   
    try:
        group = Group.objects.get(id=gid)
    except:
        error = "没有找到这个小组"
        return render_to_response('error.html', locals())   
      
    if group.user_join_groups.filter(user=request.user).count()==0:
        error = "你不是该圈子的成员"
        return render_to_response('error.html', locals())           
    if request.method == "GET":       
        return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))   
    elif request.method == "POST":
        group = Group.objects.get(id=gid)
        title = request.POST.get('title')
        content = request.POST.get('content')
        
        tlen = len(title)
        if tlen ==0:
            messages.error(request,u"标题不能为空 ")
            return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))          
        
        if tlen > 128:
            messages.error(request,u"标题长度最多64个汉字")
            return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))   
             
        clen = len(content)        
        if clen ==0:
            messages.error(request,u"内容不能为空")
            return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))   

        if clen > 8000:
            messages.error(request,u"内容长度最多4000个汉字")
            return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))             
            
        try:
            topic = Topic()
            topic.title = (title)
            topic.user = request.user
            topic.content = (content)
            topic.group = group
            topic.save()
            return HttpResponseRedirect("/group/%s/"%gid)
        except:
            import traceback
            traceback.print_exc()
            messages.error(request,u"主题添加失败了，请稍后再试")
            return render_to_response('add_topic.html', locals(),context_instance=RequestContext(request))    
        
        
        

@never_cache
@transaction.commit_on_success
def add_reply(request):
    topid = request.GET.get('topid') or request.POST.get('topid')
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/topic/%s/'%topid}))     
    if  request.method == "POST":
        
        topic = Topic.objects.get(id=topid)
        content = request.POST.get('content') or ""
        ln = len(content)
        if ln ==0:
            alert = u"内容不能为空"
            return HttpResponseRedirect("/topic/%s/?alert=%s"%(topid,alert))          
        
        if ln > 8000:
            alert = u"内容长度最多4000个汉字"
            return HttpResponseRedirect("/topic/%s/?alert=%s"%(topid,alert))   
            
        print "3333"
        try:
            comment = Comment()
            
            comment.user = request.user
            comment.content = (content)
            comment.save()
            topic.comments.add(comment)
            topic.last_update = datetime.datetime.now()
            topic.save()
            profile = request.user.get_profile()
            try:
                profile.retopics.get(id=topid)
            except:
                profile.retopics.add(topic)
                profile.save()

            return HttpResponseRedirect("/topic/%s/"%topid)
        except:
            import traceback
            traceback.print_exc()
            error = "评论添加失败了，请稍后再试"
            return render_to_response('error.html', locals()) 
    
        
    
          
